<!--- CHECKS TO SEE IF EXPERIMENT IS STILL LIVE --->
<!--- query selects start and dates from the database --->
<cfif Not IsDefined("id")>
	<cflocation url="./../error/expError" addtoken="no">
</cfif>

<cfquery datasource="exp" name="expTest">

	SELECT e.*
	FROM exper e, expstatus es
	WHERE e.id=<cfqueryparam cfsqltype="cf_sql_integer" value="#id#">
	AND e.StatusID = es.id
	AND
	(
		es.Status = 'live'
		OR
		(
			startDate <= Now()
			AND endDate > Now()
			AND maxpart > ( 
							  		SELECT count(p.id)
									FROM participant p
									WHERE p.expid = <cfqueryparam cfsqltype="cf_sql_integer" value="#id#">
						  	  )
		)
						 
	)
	
</cfquery>

<!--- check if enddate has passed or if startdate has not yet been reached   experiment.maxpart  --->
<cfif expTest.recordcount eq 0>
	<!--- query that changes live to 0 if experiment is not open --->
	<cfquery name = "closeExperiment" datasource ="exp">
	
		UPDATE exper
		SET StatusID = (
						SELECT id
						FROM expstatus
						WHERE Status = 'completed'
						)
		WHERE id = <cfqueryparam cfsqltype="cf_sql_integer" value="#id#">
	
	</cfquery>
	
	<!--- redirects to next page --->
	<cfset participant = StructNew()>
	<cfset participant.expid = id>
	<cfset session.participant = participant>
	<cflocation url="./../error/deadexp/">
</cfif>
<!--- END OF CHECK TO SEE IF EXPERIMENT IS STILL LIVE --->



<cfif IsDefined("form.yesEmail")>
	<!--- saves participants unique id and email address to database. --->
	<cfset email = "">
	<!---the way this is structured is to get arround the problem of not being able to control autocomplete hence why we have to set the answers box's id to a random indentifier. But we also have to be able to access it. There is probably a better way of doing this but this works and thats all we care about at the moment!--->
	<cfif IsDefined("form.hid_pans") AND IsDefined("form.a_" & hid_pans)>
		<cfset email = form['a_#hid_pans#']>
	<cfelse>
		<cfset participant = StructNew()>
		<cfset participant.expid = id>
		<cfset session.participant = participant>
		<cflocation url="./">
	</cfif>
	
	<cfif email neq "">
	
		<cfquery name="pexist" datasource="exp">
			SELECT *
			FROM participant
			WHERE email = <cfqueryparam cfsqltype="cf_sql_varchar" value="#email#">
			AND expid = <cfqueryparam cfsqltype="cf_sql_integer" value="#id#">
		</cfquery>
		
		<cfif #pexist.recordcount# gt 0>
			<cfset session.message = "This email has already participated in this experiment!">
			<cflocation url="ethics.cfm?id=#id#">
		</cfif>
		
		<cfquery datasource="exp" result="res">	
			
			INSERT INTO participant( expid, email, ParticipationDate)
			VALUES( <cfqueryparam cfsqltype="cf_sql_integer" value="#id#"> , <cfqueryparam cfsqltype="cf_sql_varchar" value="#email#">, Now() ) 
		
		</cfquery>
	<cfelse>
		<cfquery datasource="exp" result="res">	
			
			INSERT INTO participant( expid,  ParticipationDate)
			VALUES( <cfqueryparam cfsqltype="cf_sql_integer" value="#id#">, Now() ) 
		
		</cfquery>
	</cfif>
	
	<cfset session.expid = #id#>
	<cfset session.qcount = 1 >
	<cfset session.pid=#res.GENERATED_KEY#>
	<cfset session.prev = "">
	<cfset session.count = 0>
	
	<cfquery name = "qs" datasource="exp">
		
		SELECT id, title, isstart, expid
		FROM questionnaire
		WHERE expid = <cfqueryparam cfsqltype="cf_sql_integer" value="#id#">
		AND isstart=1

	</cfquery>

	<cfif #qs.RecordCount# eq 1>
		<cflocation url="./../Next/Questionnaire/quest.cfm?Qid=#qs.id#">
	<cfelse>
    	<!--- redirects to next page --->
		<cflocation url="./../Next/Question/index.cfm?id=#id#">
	</cfif>
<cfelse>
				 
	<cfset arrTri = ArrayNew( 1 )>


	<cfquery name = "alltri" datasource="exp">
		
		SELECT sq.id
		FROM StimQuestions sq, stim s, conditions c
		WHERE c.expid = <cfqueryparam cfsqltype="cf_sql_integer" value="#id#">
		AND c.id = s.CondID
		AND s.id = sq.StimID 
   
	</cfquery>

   <cfset arrTri = ArrayNew( 1 ) />
	
   <!--- adds trials to their blocks --->
	<cfloop query = "alltri">
	
	   <cfset ArrayAppend(arrTri, alltri.id) /> 
	     
	   <!--- Loop over the array N times. --->
		<cfloop index="j" from="1" to="#ArrayLen(arrTri )#" step="1">
		
		  <!--- Swap the current item with a randomly chosen item. We are getting the random index via RandRange(). --->
		  <cfset ArraySwap(arrTri, j, RandRange( 1, ArrayLen( arrTri ) ) ) />   	
		  
		</cfloop>
		
	</cfloop>
	  					
	<cfset session.arrTri=#arrTri#>


	<!--- selects the experiment, and retrieves the experiments unique
	  --- id, its name, its description and the ethics form from the database. --->
	<cfquery name = "u" datasource="exp">
		
		SELECT id, title, description, ethicsID
		FROM exper
		WHERE id = <cfqueryparam cfsqltype="cf_sql_integer" value="#id#">

	</cfquery>
	
	<!--- reads file --->

	<cfinclude template= "./../pheader.cfm">	

	<cfoutput>
		<!--- What the page will display to the participant --->
		<div style="margin-left:auto; margin-right: auto; width:750px">
		<h2>Welcome to the #u.title# experiment</h2>
		<cfquery datasource="exp" name="filestore">
			SELECT *
			FROM filestore
			WHERE id = #u.ethicsID#
		</cfquery>
		
		<br/>
        
		<div>
			<embed src="/ecada/files/#filestore.filepath#/#filestore.filename###toolbar=0&navpanes=0" width="750" height="500">
			<center>Alternativly download this form: <a href="/ecada/files/#filestore.filepath#/#filestore.filename#" style="color: red;">#filestore.filename#</a></center>
		</div>
		
		<br/>
		
	
		<script type="text/javascript">
			
			function Agree(cb)
			{
				if(cb.checked)
				{
					$('##acceptor').show('slow');
					$('##a_'+$('##hid_pans').val()).focus();
					$('##yesEmail').removeAttr('disabled');
				}
				else
				{
					$('##acceptor').hide('slow');
					$('##yesEmail').attr('disabled', 'true');
				}
				$('##container').redrawShadow();
				$('##innercontent').redrawShadow();
			}
			
			$(document).ready(function() {
				$('##agree').attr('checked', false);
				$('.checked').attr('class', 'unchecked');
			});
		</script>
		<center style="padding-bottom: 16px;" >
			<b>Do you agree to the above?</b>
				<input name="agree" id="agree" type="CHECKBOX" onclick="Agree(this);"/>
			</br>
		</center>
		<!--- text box and submit button for their email address --->	
		<div id="acceptor" name="acceptor" class="ui-corner-all" style="background-image:url('/ecada/css/images/bg.png');margin-bottom: 5px; padding: 16px; border: 4px solid black; display: none; margin-top:5px width: 750px">
			<p>It is not compulsory to give your email and if you do not wish to submit your email address then please just click continue. If you do not give your email address you will not be able to be notified of the results of the experiment and your participation will be completly anonymous.</p>
			<div style="margin-left: auto; margin-right: auto; width: 75%;">
				<form method="post" action="./ethics.cfm?id=#id#">
					<table>
						<tr>
							<td>	
								Email Address:
							</td>
							<td>
								<cfset chars = "0123456789abcdefghiklmnopqrstuvwxyz" / >
								<cfset strLength = 6 / >
								<cfset randout = "" / >

								<cfloop from="1" to="#strLength#" index="i">
									<cfset rnum = ceiling(rand() * len(chars)) / >
									<cfif rnum EQ 0 ><cfset rnum = 1 / ></cfif>
									<cfset randout = randout & mid(chars, rnum, 1) / >
								</cfloop>
								
								<input type="hidden" name="hid_pans" id="hid_pans" value="#randout#">
								<input type="text" style="width: 350px;" name="a_#randout#" id="a_#randout#"  value="">
							</td>
						</tr>
					</table>
					</br>
					<div style="width: 150px; height: 50px; margin-left: auto; margin-right: auto;">
						<button class="ui-state-default ui-corner-all" type="submit" name="yesEmail" id="yesEmail" disabled="true" style="width: 150px; height: 50px;" ><strong>Continue</strong></button>					
					</div>
					</br>
				</form>
			</div>
		</div>
		<br />
	</div>
	</cfoutput>
</cfif>

